/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.*;

/**
 * Writes a simple .xml or binary file out of an double[][] matrix
 *
 * @author Corvus
 */
public class MatrixWriter {

    /**
     * Writes the XML file
     *
     * @param matrix The matrix to write into a file
     * @param fileName The .xml file's filename
     * @throws IOException
     */
    public static void writeXML(double[][] matrix, String fileName) throws IOException {
        int rows = matrix.length;
        int columns = matrix[0].length;

        File f = new File(fileName);
        if (f.exists()) {
            f.delete();
        }

        FileWriter out = new FileWriter(f);

        out.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        out.append("<!DOCTYPE matrix SYSTEM \"matrix.dtd\">\n");

        out.append("<matrix rows=\"" + rows + "\" columns=\"" + columns + "\">\n");

        for (int y = 0; y < matrix.length; y++) {
            out.append("\t<row>\n");
            for (int x = 0; x < matrix[y].length; x++) {
                out.append("\t\t<value>" + matrix[y][x] + "</value>\n");
            }
            out.append("\t</row>\n");
            out.flush();
        }

        out.append("</matrix>\n");

        out.flush();
        out.close();
    }

    /**
     * Writes a binary file out of the matrix.
     * 
     * @param matrix The matrix to write into a file
     * @param fileName The binary file's filename
     * @throws IOException
     */
    public static void writeBinary(double[][] matrix, String fileName) throws IOException {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
        out.writeObject(matrix);
        out.flush();
        out.close();
    }
}
